package ar.com.e2solver.solver;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class RouletteWheelSelector {

	public static List<Individual> select(Population population, int numberOfSelections) {
		List<Individual> selectionCandidates = new ArrayList<Individual>(population.getIndividuals());
		List<Individual> selection = new ArrayList<Individual>();
		int totalFitness = getTotalFitness(selectionCandidates);
		
		for(int i = 0; i < numberOfSelections; i++){

			int selectedNumber = RandomConstants.RANDOM.nextInt(totalFitness);
			int acum = 0;
			
			for (int j = 0; j < selectionCandidates.size(); j++) {
				Individual individual = selectionCandidates.get(j);
				acum += individual.getFitnessValue();
				
				if(selectedNumber < acum){
					selection.add(individual);
					selectionCandidates.remove(j);
					totalFitness = totalFitness - individual.getFitnessValue();
					break;
				}
			}
		}
		
		return selection;
	}

	private static int getTotalFitness(List<Individual> selectionCandidates) {
		int totalFitness = 0;
		for (Iterator<Individual> iterator = selectionCandidates.iterator(); iterator.hasNext();) {
			Individual individual = iterator.next();
			totalFitness += individual.getFitnessValue();
		}
		
		return totalFitness;
	}

}
